package com.bonorsoft.system.controller;

import com.bonorsoft.common.api.Result;
import com.bonorsoft.system.entity.SysMoney;
import com.bonorsoft.system.entity.SysSet;
import com.bonorsoft.system.service.SysMoneyService;
import com.bonorsoft.util.oConvertUtils;
import com.bonorsoft.system.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/wxpay")
public class SendPayController {
    @Autowired
    private SysMoneyService moneyService;

    /**
     * 根据openid进行缴费
     * @param money
     * @param request
     * @return
     */
    @PostMapping(value = "/orders")
    public Result<?> wxPay(@RequestBody SysMoney money, HttpServletRequest request) {
        return moneyService.wxPay(money, request);
    }

    /**
     * @Title: callBack
     * @Description: 支付完成的回调函数
     * @param:
     * @return:
     */
    @RequestMapping("/notify")
    public String callBack(HttpServletRequest request, HttpServletResponse response) {
        // System.out.println("微信支付成功,微信发送的callback信息,请注意修改订单信息");
        InputStream is = null;
        try {

            is = request.getInputStream();// 获取请求的流信息(这里是微信发的xml格式所有只能使用流来读)
            String xml = WXPayUtil.inputStream2String(is);
            Map<String, String> notifyMap = WXPayUtil.xmlToMap(xml);// 将微信发的xml转map

            System.out.println("微信返回给回调函数的信息为：" + xml);

            if (notifyMap.get("result_code").equals("SUCCESS")) {
                String openid = notifyMap.get("openid");// 实际支付的订单金额:单位 分
                String ordersSn = notifyMap.get("out_trade_no");// 商户订单号
                String amountpaid = notifyMap.get("total_fee");// 实际支付的订单金额:单位 分
                BigDecimal amountPay = (new BigDecimal(amountpaid).divide(new BigDecimal("100"))).setScale(2);// 将分转换成元-实际支付金额:元

                moneyService.updateStatusBySql(openid,ordersSn);

                /*
                 * 以下是自己的业务处理------仅做参考 更新order对应字段/已支付金额/状态码
                 */
                System.out.println("===notify===回调方法已经被调！！！");

            }

            // 告诉微信服务器收到信息了，不要在调用回调action了========这里很重要回复微信服务器信息用流发送一个xml即可
            response.getWriter().write("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }

    /**
     * 取消订单
     * @param money
     * @return
     */
    @PostMapping(value = "/cancel")
    public Result<?> cancelOrder(@RequestBody SysMoney money){
        moneyService.cancelOrder(money.getOpenid(),money.getOutTradeNo());
        return Result.ok("取消成功！");
    }

    /**
     * 用户是否缴费
     * @param openid
     * @return
     */
    @GetMapping(value = "/index")
    public Result<?> homePage(@RequestParam(name="openid",required=true) String openid){
        SysMoney sysMoney = moneyService.paymentConditions(openid);
        return sysMoney != null ? Result.ok(sysMoney) : Result.error("开始缴费！");
    }


    /**
     * 缴费人数是否已满
     * @return
     */
    @GetMapping(value = "/full")
    public Result<?> peopleFull(){
        //true-人数已满
        boolean b = moneyService.peopleFull();
        return b ? Result.ok("人数已满") : Result.error("人数未满");
    }


    /**
     * 判断缴费是否开始
     * @return
     */
    @GetMapping(value = "/scan")
    public Result<?> scanCode() {
        SysSet basic = moneyService.getBasic();
        Date startTime = basic.getStartTime();
        Date endTime = basic.getEndTime();
        Date today = new Date();
        if(oConvertUtils.isNotEmpty(startTime) || oConvertUtils.isNotEmpty(endTime)){
            if(today.getTime() < startTime.getTime()){
                return Result.error("还未开始缴费，请耐心等待!（开始时间："+ new SimpleDateFormat("yyyy/MM/dd HH:mm").format(startTime) +"—" +
                        "结束时间："+ new SimpleDateFormat("yyyy/MM/dd HH:mm").format(endTime) +"）");
            }
            if(today.getTime() > endTime.getTime()){
                return Result.error("缴费已截止!（开始时间："+ new SimpleDateFormat("yyyy/MM/dd HH:mm").format(startTime) +"—" +
                        "结束时间："+ new SimpleDateFormat("yyyy/MM/dd HH:mm").format(endTime) +"）");
            }
            if(today.getTime() >= startTime.getTime() && today.getTime() <= endTime.getTime()){
                return Result.ok("正常缴费时间！");
            }
        }else{
            return Result.error("系统未设置缴费时间段！");
        }
        return Result.error("错误时间段！");

    }

    /**
     * 获取基础设置信息
     * @return
     */
    @GetMapping(value = "/query")
    public Result<?> queryBasic(){
        SysSet sysBasic = moneyService.getBasic();
        return Result.ok(sysBasic);
    }

    /**
     * 添加缴费开始和结束时间
     * @param basic
     * @return
     */
    @PostMapping(value = "/set")
    public Result<?> basicSet(@RequestBody SysSet basic){
        moneyService.saveBasic(basic);
        return Result.ok("添加成功");
    }

    /**
     * 编辑缴费开始和结束时间
     * @param basic
     * @return
     */
    @PostMapping(value = "/edit")
    public Result<?> editBasicSet(@RequestBody SysSet basic){
        moneyService.updateBasicById(basic);
        return Result.ok("编辑成功");
    }

    /**
     * 无用方法
     * @return
     */
    @GetMapping(value = "/test")
    public Result<?> test(){
        moneyService.updateStatus("of-Oq5cmF2_xrzOEMfB8THtMWOEg","202008181597711308161");
        return Result.ok("sss");
    }
}
